//
//  CurrentConstructHeaderView.m
//  Runone
//
//  Created by runone02 on 16/12/6.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "CurrentConstructHeaderView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "Masonry.h"
#import "Define.h"
#import "AppConstants.h"
#import "AppDelegate.h"
#import "PileInfo.h"
#import "CustomAnnotationView.h"
#import "CustomCallOutView.h"
#import "ROPointAnnotation.h"
#import "RightCodeTool.h"
#import "OneConst.h"
#import "HighwayMergeInfoModel.h"
#import "StationModel.h"
#import "NSDate+ROCaculateTime.h"
#import "NSDate+Addition.h"

@interface CurrentConstructHeaderView () <MAMapViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *mapBackGroundView;
@property (weak, nonatomic) IBOutlet MAMapView *mapView;

@property (weak, nonatomic) IBOutlet UIButton *traffiBtn;

//****************---*********************************************
@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UILabel *pileNOLabel;
@property (weak, nonatomic) IBOutlet UILabel *directionLabel;
@property (weak, nonatomic) IBOutlet UILabel *timeTipsLabel;
@property (weak, nonatomic) IBOutlet UILabel *lastTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *beginTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;

//****************---*********************************************
@property (weak, nonatomic) IBOutlet UILabel *departmentLabel;
@property (weak, nonatomic) IBOutlet UILabel *headerLabel;
@property (weak, nonatomic) IBOutlet UILabel *contacterNO;

//************************************** -3- **************************************
@property (weak, nonatomic) IBOutlet UILabel *contentTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;

//********************************** -4- **********************************
@property (weak, nonatomic) IBOutlet UILabel *dealProgressLabel;
//****************---*********************************************

//@property (nonatomic,strong)NSMutableArray *annotationsArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cameraGunWidth;

@end

@implementation CurrentConstructHeaderView

#pragma    ----------施工事件详情

//路况按钮点击
- (IBAction)traficBtnClick:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        _mapView.showTraffic=YES;
    } else {
        _mapView.showTraffic=NO;
    }

}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor  = [UIColor colorWithRed:244.0/255 green:244.0/255 blue:244.0/255 alpha:1];
    _mapView.delegate     = self;
    _mapView.showsCompass = NO;
    _mapView.showsScale   = NO;
    _iconImg.image        = [UIImage imageNamed:@"event_construct_main_icon"];
    [self configTextColor];
    _cameraArray = [[NSMutableArray alloc] init];
}
#pragma mark -设置label的字体颜色
- (void) configTextColor {
    _pileNOLabel.textColor       = kTableViewCellTextColor;
    _directionLabel.textColor    = kTableViewCellTextColor;
    _timeTipsLabel.textColor     = kTableViewCellTextColor;
    _lastTimeLabel.textColor     = kTableViewCellTextColor;
    _beginTimeLabel.textColor    = kTableViewCellTextColor;
    _endTimeLabel.textColor      = kTableViewCellTextColor;
    
    _departmentLabel.textColor   = kTableViewCellTextColor;
    _headerLabel.textColor       = kTableViewCellTextColor;
    _contacterNO.textColor       = kTableViewCellTextColor;
    
    _contentTitleLabel.textColor = kTableViewCellTextColor;
    _contentLabel.textColor      = kTableViewCellTextColor;

}

//设置模型
- (void) setCeModel:(CurrentEvent *)ceModel {
    _ceModel = ceModel;
    [self loadEventAnnotation];
     [self gerAllTheDirectionCameraArray];
//    [self getTheWantCameraGun];
    [self getMostLeastCameraGun];
    [self configToolView];
}

- (void) gerAllTheDirectionCameraArray {
    [_cameraArray removeAllObjects];
    
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *model in myDelegate.HighWayRoadArray) {
        if ([model.RoadUID isEqualToString:_ceModel.RoadUID]) {
            _currentRoadModel = model;
        }
    }
    
    if ([_ceModel.RoadDerection integerValue] == RoadTypeUp) {
        for (HighwayMergeInfoModel *mergeInfoModel in _currentRoadModel.mergeInfoList) {
            [self getAllWantCamera:mergeInfoModel.UpWayDevices andDirection:DirectionTypeUp];
        }
    }
    
    if ([_ceModel.RoadDerection integerValue] == RoadTypeDown) {
        for (HighwayMergeInfoModel *mergeInfoModel in _currentRoadModel.mergeInfoList) {
            [self getAllWantCamera:mergeInfoModel.DownWayDevices andDirection:DirectionTypeDown];
        }
    }
    
    //    AppDelegate *myDelegate  = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if ([_ceModel.RoadDerection integerValue] == RoadTypeUpAndDown) {
        for (DeviceBaseInfo *moel in myDelegate.AllDeviceBaseArray) {
            if (moel.DeviceType == DevicesTypeCamera && [moel.RoadUID isEqualToString:_currentRoadModel.RoadUID]) {
                [_cameraArray addObject:moel];
            }
        }
    }
}

- (void)getAllWantCamera:(NSArray *)array andDirection:(DirectionType)type {
    for (DeviceBaseInfo *model in array) {
        if ((model.DeviceType == 4 && model.Direction == type) || (model.DeviceType == 4 && model.Direction == DirectionTypeUPAndDown)) {
            [_cameraArray addObject:model];
        }
    }
}

- (void)setEventModel:(EventDetailModel *)eventModel {
    _eventModel = eventModel;
    NSString *rampStr;
    if (eventModel.EventBaseInfo.TollStationUID) {
        AppDelegate *myDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        for (StationModel *model in myDelegate.AllTollStationArray) {
            if ([model.TollStationUID isEqualToString:eventModel.EventBaseInfo.TollStationUID]) {
                NSString *station     = [NSString stringWithFormat:@"%@施工",model.TollStationName];
                _directionLabel.text = [NSString stringWithFormat:@"%@ %@",_eventModel.EventBaseInfo.RoadDerectionName, station];
            }
        }
    }else {
        if (eventModel.EventBaseInfo.IsRamp) {
            rampStr = @"匝道施工";
        } else {
            rampStr = @"主线施工";
        }
        if (_eventModel.EventBaseInfo.RoadDerectionName) {
             _directionLabel.text = [NSString stringWithFormat:@"%@ %@",_eventModel.EventBaseInfo.RoadDerectionName, rampStr];
        }else {
         _directionLabel.text = [NSString stringWithFormat:@"%@", rampStr];
        }
    }
    
    if ([_ceModel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        _pileNOLabel.text    = [NSString stringWithFormat:@"%@+%@至%@+%@",_ceModel.BeginPile,_ceModel.BeginPileDistance,_ceModel.EndPile,_ceModel.EndPileDistance];
    } else {
        if (_ceModel.BeginPile ) {
            NSString *LStr       = @"L";
            NSString *beginLKStr = [LStr stringByAppendingString:_ceModel.BeginPile];
            NSString *endLKStr   = [LStr stringByAppendingString:_ceModel.EndPile];
            _pileNOLabel.text    = [NSString stringWithFormat:@"%@+%@至%@+%@",beginLKStr,_ceModel.BeginPileDistance,endLKStr,_ceModel.EndPileDistance];
        }else {
            _pileNOLabel.text = @"";
        }
    }
    
    if(_eventModel.EventBaseInfo.OccurTime == nil) {
        _beginTimeLabel.text = [NSString stringWithFormat:@"计划开始时间"];
    }else {
        _beginTimeLabel.text = [NSString stringWithFormat:@"计划开始时间:%@",_eventModel.EventBaseInfo.OccurTime];
    }
    
    if(_eventModel.EventBaseInfo.OccurTime == nil) {
        _endTimeLabel.text = [NSString stringWithFormat:@"计划结束时间"];
    }else {
        _endTimeLabel.text = [NSString stringWithFormat:@"计划结束时间:%@",_eventModel.EventBaseInfo.EndTime];
    }
    
    _contentLabel.text   = _eventModel.Content;
    //*************公司
//    NSArray *array = [_eventModel.Department componentsSeparatedByString:@"公司"];
//    NSString *fisrtStr = array[0];
//    NSString *secondStr = array[1];
//    NSString *startStr = @"";
//    for (int i = 0; i < fisrtStr.length; i++) {
//        startStr = [startStr stringByAppendingString:@"*"];
//    }
//    NSString *aStr = [startStr stringByAppendingString:@"公司"];
//    NSString *bStr ;
//    if (startStr.length > 0) {
//        bStr = [aStr stringByAppendingString:secondStr];
//    }
//    _departmentLabel.text = [NSString stringWithFormat:@"施  工  单  位 :%@",bStr];
//    
//    NSInteger headerlength = _eventModel.Header.length;
    if (_eventModel.Department) {
            _departmentLabel.text = [NSString stringWithFormat:@"施  工  单  位 :%@",_eventModel.Department];
    }else {
    _departmentLabel.text = [NSString stringWithFormat:@"施  工  单  位 :"];
    }
    
//    // 林**
//    if (headerlength > 3) {
//        NSString *headerLastStr = @"";
//        NSInteger lastLen = headerlength - 3;
//        for (int i = 0; i <= lastLen ; i ++) {
//          headerLastStr =  [headerLastStr stringByAppendingString:@"*"];
//        }
//        NSString *fisrtNameStr = [_eventModel.Header substringWithRange:NSMakeRange(0, 2)];
//        NSString *nameStr = [fisrtNameStr stringByAppendingString:headerLastStr];
//        _headerLabel.text   = [NSString stringWithFormat:@"现 场 负 责 人 :%@",nameStr];
//    }else {
//     NSString *headerLastStr = @"";
//        NSInteger lastLen = headerlength - 1;
//        for (int i = 0; i <= lastLen ; i ++) {
//            headerLastStr =  [headerLastStr stringByAppendingString:@"*"];
//        }
//        NSString *fisrtNameStr = [_eventModel.Header substringWithRange:NSMakeRange(0, 1)];
//        NSString *nameStr = [fisrtNameStr stringByAppendingString:headerLastStr];
//        _headerLabel.text   = [NSString stringWithFormat:@"现 场 负 责 人 :%@",nameStr];
//    }
    if (_eventModel.Header) {
        _headerLabel.text   = [NSString stringWithFormat:@"现 场 负 责 人 :%@",_eventModel.Header];
    }else{
        _headerLabel.text   = [NSString stringWithFormat:@"现 场 负 责 人 "];
    }
    
    //152**********
//    NSString *phoneLastStr = @"";
//    for (int i = 0; i < 8; i ++) {
//        phoneLastStr = [phoneLastStr stringByAppendingString:@"*"];
//    }
//    NSString *phoneFirstStr = [_eventModel.Telephone substringWithRange:NSMakeRange(0, 3)];
//    NSString *telStr = [phoneFirstStr stringByAppendingString:phoneLastStr];
//    _contacterNO.text  = [NSString stringWithFormat:@"联系电话:%@",telStr];
//    
//    if (_eventModel.Content) {
//        _contentLabel.text    = [NSString stringWithFormat:@"%@",_eventModel.Content];
//    }
    if (_eventModel.Telephone) {
        _contacterNO.text  = [NSString stringWithFormat:@"联系电话:%@",_eventModel.Telephone];
    }else {
        _contacterNO.text  = [NSString stringWithFormat:@"联系电话:"];
    }
    
    NSDateComponents *com = [NSDate componentsFrom:_eventModel.EventBaseInfo.OccurTime];
    
    _lastTimeLabel.text = [NSString stringWithFormat:@"%ld天%ld小时%ld分",(long)com.day,(long)com.hour,(long)com.minute];
}

#pragma mark - 加载地图事件标注
- (void)loadEventAnnotation { //0.232529--0.300532--11.526650--24.709414--113.471923--326.931946
    
    AppDelegate *myDelegate = (AppDelegate*) [UIApplication sharedApplication].delegate;
    NSArray *pileArray =  myDelegate.PirArray;
    NSString *pileStr  = _ceModel.BeginPile;
    for (PileInfo *pileModel in pileArray) {
        if ([pileStr isEqualToString: pileModel.PileNo] && [pileModel.RoadUID isEqualToString:_ceModel.RoadUID]) {
            _ceModel.Latitude = [NSString stringWithFormat:@"%f",pileModel.Latitude];
            _ceModel.Longitude =[NSString stringWithFormat:@"%f", pileModel.Longitude];
        }
    }
    ROPointAnnotation *roAnnotation = [[ROPointAnnotation alloc] init];
    float latitude = [_ceModel.Latitude floatValue];
    float longitude = [_ceModel.Longitude floatValue];
    
    MACoordinateSpan  span                  = MACoordinateSpanMake(0.232529, 0.300532);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
    MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
    _mapView.region           = region;

    [_mapView setCenterCoordinate:centerCoordinate animated:NO];
    _mapView.zoomLevel = 11.214808;
    
    CLLocationCoordinate2D ret = CLLocationCoordinate2DMake(latitude, longitude);
    roAnnotation.coordinate = ret;
    _ceModel.Latitude = [NSString stringWithFormat:@"%f",ret.latitude];
    _ceModel.Longitude = [NSString stringWithFormat:@"%f",ret.longitude];
    roAnnotation.currentEventModel = _ceModel;
    [_mapView addAnnotation:roAnnotation];

}

#pragma mark - 判断摄像枪
- (void)getTheWantCameraGun {
    if ([_ceModel.RoadDerection integerValue] == 1) { //上行
        _cameraArray = [self getTheWantCameraDevice:_ceModel.RoadDerection ];
    }
    
    if ([_ceModel.RoadDerection integerValue] == 2) { // 下行
        _cameraArray = [self getTheWantCameraDevice:_ceModel.RoadDerection];
    }
    
    if ([_ceModel.RoadDerection integerValue] == 3) { //双向
        _cameraArray = [self  getAllCameraGun];
    }
}

- (NSMutableArray *) getTheWantCameraDevice:(NSString *)roadDeretion {
    AppDelegate *myDelegate  = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray = myDelegate.AllDeviceBaseArray ;
    NSMutableArray *wantCameraDevice = [[NSMutableArray alloc] init];
    
    for (DeviceBaseInfo *model in dataSourceArray) {
        if (model.DeviceType == DevicesTypeCamera && (model.Direction == [roadDeretion integerValue] || model.Direction == 3)) {
            [wantCameraDevice addObject:model];
        }
    }
    return wantCameraDevice;
}

- (NSMutableArray *) getAllCameraGun {
    AppDelegate *myDelegate  = (AppDelegate*) [UIApplication sharedApplication].delegate ;
    NSArray *dataSourceArray = myDelegate.AllDeviceBaseArray ;
    NSMutableArray *wantCameraDevice = [[NSMutableArray alloc] init];
    
    for (DeviceBaseInfo *model in dataSourceArray) {
        if (model.DeviceType == DevicesTypeCamera ) {
            [wantCameraDevice addObject:model];
        }
    }
    return wantCameraDevice;
}


#pragma mark -找到最近的摄像枪
- (void) getMostLeastCameraGun {
    NSArray *incidentArray = [_ceModel.BeginPile componentsSeparatedByString:@"K"];
    NSString *incientStr   = incidentArray[1];
    NSInteger incientInter = [incientStr integerValue] * 1000 + [_ceModel.BeginPileDistance integerValue]; //事件
    
    NSMutableArray *intArray = [[NSMutableArray alloc] init];
    
    for (DeviceBaseInfo *model in _cameraArray) {
        
        NSArray *strArray = [model.PileNo componentsSeparatedByString:@"K"];
        NSString * str = [strArray lastObject];
        NSInteger inter = [str integerValue] * 1000 + model.PileDistance;
        
        NSInteger marginInt = labs(incientInter - inter);
        NSNumber *num       = [NSNumber numberWithInteger:marginInt];
        [intArray addObject:num]; //差值的数组
    }
    
    if (intArray.count == 0)  return;
    
    NSNumber *minValue = [intArray valueForKeyPath:@"@min.floatValue"];
    NSUInteger index   = [intArray indexOfObject:minValue];
    
    _deviceMoel = _cameraArray[index]; //最近的摄像枪模型
}

#pragma mark - 显示摄像枪的桩号
- (void)configToolView {
    NSString *beginPileNO = [NSString stringWithFormat:@"%@",_deviceMoel.PileNo];
    NSString *pileDistance = [NSString stringWithFormat:@"%ld",(long)_deviceMoel.PileDistance];
    
    if (_deviceMoel) {
        _cameraGunBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        
        [_cameraGunBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 25, 0, 0)];
        
        if ([_deviceMoel.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
            [_cameraGunBtn setTitle:[NSString stringWithFormat:@"%@+%@",beginPileNO, pileDistance] forState:UIControlStateNormal];
        }else {
        NSString *lStr  = @"L";
        NSString *lKStr = [lStr stringByAppendingString:beginPileNO];
        [_cameraGunBtn setTitle:[NSString stringWithFormat:@"%@+%@",lKStr, pileDistance] forState:UIControlStateNormal];
        }

        
        [_cameraGunBtn setTintColor:[UIColor whiteColor]];
       _cameraGunWidth.constant = [self caculateCameraGunBtnWidth] + 25 + 10; // 25 为图片向左偏移量 10为校准值
        [_mapBackGroundView layoutIfNeeded];

    }
    if (!_deviceMoel) {
        _cameraGunBtn.hidden = YES;
    }
}
#pragma mark -计算摄像枪按钮的宽度
- (CGFloat ) caculateCameraGunBtnWidth {
    CGSize maxSize   = CGSizeMake(MAXFLOAT, 30);
   CGFloat width = [_cameraGunBtn.titleLabel.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:13]} context:nil].size.width;
    return width;
}


#pragma mark -地图代理
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.calloutView.hidden = YES;
        annotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
        if (_ceModel.IsRamp) {
            annotationView.image = [UIImage imageNamed:@"ramp_construction"];
        }else {
        annotationView.image = [UIImage imageNamed:@"main_line_construction"];//施工图标
        }
        annotationView.centerOffset = CGPointMake(0, -annotationView.image.size.height / 2);
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    CustomAnnotationView *customView = (CustomAnnotationView *)view;
    if (customView.CEModel) {
        customView.selected           = NO;
        customView.canShowCallout     = NO;
    }
    customView.calloutView.hidden = YES;
}
-(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    NSLog(@"%f--%f--%f--%f--%f--%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta,mapView.zoomLevel,mapView.region.center.latitude,mapView.region.center.longitude, mapView.rotationDegree);
}


@end
